﻿using AutoMapper;
using BS.Domain.RBAC;
using BS.Infra;
using BS.Infra.Interface;
using MediatR;

namespace BS.Read.Api.Handler.RBAC
{
    public class GetUserWithRoleHandler : IRequestHandler<GetUserWithRoleRequestDTO, ApiResult>
    {
        private readonly ILogger<GetUserWithRoleHandler> _logger;

        private readonly IUserRepository _userRepository;

        private readonly IRoleRepository _roleRepository;

        private readonly IUserRoleRepository _useroleRepository;

        private readonly IMapper _mapper;
        public GetUserWithRoleHandler(ILogger<GetUserWithRoleHandler> logger, IUserRepository userRepository, IRoleRepository roleRepository, IMapper mapper, IUserRoleRepository useroleRepository)
        {
            _logger = logger;
            _userRepository = userRepository;
            _roleRepository = roleRepository;
            _mapper = mapper;
            _useroleRepository = useroleRepository;
        }
        public async Task<ApiResult> Handle(GetUserWithRoleRequestDTO request, CancellationToken cancellationToken)
        {
            try
            {
                var userList = await _userRepository.GetAllAsync(x=>x.IsDeleted==false);
                var roleList = await _roleRepository.GetAllAsync(x => x.IsDeleted == false);
                var urList=await _useroleRepository.GetAllAsync();
                var list=from UserInfo in userList
                         join Role in roleList 
                         on UserInfo.RoleId equals Role.RoleId
                         join UserRole in urList
                         on UserInfo.UserId equals UserRole.UserId
                         select new GetUserWithRoleReponseDTO()
                         {
                             UserId = UserInfo.UserId,
                             UserName = UserInfo.UserName,              
                             RoleId = Role.RoleId,
                             RoleName = Role.RoleName,
                             URId=UserRole.URId
                         };

                return await Task.FromResult(ApiResult.Ok(list));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "GetUserWithRoleHandler");
                return await Task.FromResult(ApiResult.Fail(ex.Message));
            }
        }
    }
}
public class GetUserWithRoleRequestDTO:IRequest<ApiResult>
{

}
public class GetUserWithRoleReponseDTO
{
    public int UserId { get; set; }

    public string UserName { get; set; } = string.Empty;

    public int RoleId { get; set; }

    public string RoleName { get; set; } = string.Empty;

    public int URId { get; set; }
}